import { getVNodeChildren } from 'naive-ui/es/_utils';
import type { RouteRecordRaw, RouteComponent, RouteMeta } from 'vue-router';
import type { RouteRequestItem, RouteFormatItem, RouteFormatItemType } from './map-menus.type';
import router from '../router/index'

// 处理路径
const loadView = async (component: string) => {
    // return (resolve) => require([`@/view/${component}`], resolve);
    // return await import(`../view/${component}`);
}
// vite处理路径方法，匹配文件路径
function _getModules(): any {
    const components = import.meta.glob('@/view/Layout/**/*.vue')
    let result:Array<any> = [];
    Object.entries(components).forEach(item => {
        result.push(item);
    })
    return result;
}

// 处理后台返回的路由表
export function formatRoutes(routes: RouteRequestItem[]): RouteRecordRaw[] {
    let componentList = _getModules();
    const formatRouteArr: RouteRecordRaw[] = [];
    // const _modules = import.meta.glob('../view/**/*.vue');
    routes.forEach((route: RouteRequestItem) => {
        // 定义路由列表对象
        const routerItem: RouteRecordRaw | any = { meta: {} };
        // 结构接收到的数据对象
        const { id, pid, children, title, name, path, icon, sort, type, roles, keep_alive } = route;
        // 判断是否有子级
        if (children && children instanceof Array && children.length > 0) {
            // 递归处理子级
            routerItem['children'] = formatRoutes(children);
        } else {
            // 处理动态路由
            let res = componentList.find((mod: any) => mod[0].indexOf(path) !== -1);
            routerItem['component'] = res[1];
            // router['component'] = _modules['../views/' + path + '.vue'];

        }
        // 处理其他参数
        routerItem['id'] = id || null;
        routerItem['pid'] = pid || null;
        routerItem['path'] = path || null;
        routerItem.meta!['title'] = title || null;
        routerItem.meta!['name'] = name || null;
        routerItem.meta!['icon'] = icon || null;
        routerItem.meta!['sort'] = sort || null;
        routerItem.meta!['type'] = type || null;
        routerItem.meta!['roles'] = roles || null;
        routerItem.meta!['keep_alive'] = keep_alive || false;

        // 动态添加路由
        router.addRoute('Layout', routerItem);
        
        formatRouteArr.push(routerItem);
    })
    return formatRouteArr;
}



// export function mapMenusToRoutes(userMenus: any[]): RouteRecordRaw[] {
//     const routes: RouteRecordRaw[] = [];
//     console.log("接收传进来的参数", userMenus);
//     console.log(require)
//     return routes;
// }